import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')
  const avatar = ref('')

  // 登录
  const login = async (loginForm) => {
    try {
      const { data } = await request.post('/api/auth/login', loginForm)
      token.value = data.token
      username.value = data.username
      avatar.value = data.avatar || ''
      
      // 保存到本地存储
      localStorage.setItem('token', data.token)
      localStorage.setItem('username', data.username)
      
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    username.value = ''
    avatar.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const { data } = await request.get('/api/auth/info')
      username.value = data.username
      avatar.value = data.avatar || ''
      localStorage.setItem('username', data.username)
    } catch (error) {
      ElMessage.error(error.message || '获取用户信息失败')
    }
  }

  return {
    token,
    username,
    avatar,
    login,
    logout,
    getUserInfo
  }
}) 